package cn.wolfcode.wolf2w.gateway.filter;

import cn.wolfcode.wolf2w.common.core.domain.R;
import cn.wolfcode.wolf2w.common.redis.service.RedisService;
import cn.wolfcode.wolf2w.common.redis.util.RedisKeys;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

@Component
public class BrushFilter implements GlobalFilter {

    @Autowired
    private RedisService redisService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取ip 和 key进行拼接
        //获取到请求地址中的url
        String url = exchange.getRequest().getURI().getPath();
        //如果使用代理服务，无法获取真实的ip地址
        //使用公司写好的工具类取得ip地址
        String ip = exchange.getRequest().getRemoteAddress().getAddress().toString();
        //拼接前奏，获取rediskeys
        String key = RedisKeys.BRUSH.join(url, ip);
        //方法调用，如果没有就重置时间为20,如果存在不进行覆盖
        redisService.setNXCacheObject(key, 20,RedisKeys.BRUSH.getTime(), TimeUnit.SECONDS);
        //得到的访问次数后剩余的值
        Long d = redisService.incrementCacheObjectValue(key, -1);
        if (d < 0){
            //找到应答对象的header
            HttpHeaders headers = exchange.getResponse().getHeaders();
            //
            headers.setContentType(MediaType.APPLICATION_JSON);
            R<Object> r = R.fail(500, "请勿频繁访问");
            //注解中使用了restcontroller，所以不用json，只要下面的databuffer
            String s = JSON.toJSONString(r);
            DataBuffer dataBuffer = exchange.getResponse().bufferFactory().wrap(s.getBytes(StandardCharsets.UTF_8));
            return exchange.getResponse().writeWith(Mono.just(dataBuffer));
        }
        //放行
        return chain.filter(exchange);
    }
}
